﻿namespace Attacher
{
	using Microsoft.Win32;

	using System;

	internal class AutoStartService : IAutoStartService
	{
		private const string RunLocation = @"Software\Microsoft\Windows\CurrentVersion\Run";

		/// <summary>
		/// Sets the autostart value for the assembly.
		/// </summary>
		/// <param name="keyName">Registry Key Name</param>
		/// <param name="assemblyLocation">Assembly location (e.g. Assembly.GetExecutingAssembly().Location)</param>
		public void SetAutoStart(string keyName, string assemblyLocation)
		{
			ParameterChecker.IsNotNullOrEmpty(keyName, "keyName");
			ParameterChecker.IsNotNullOrEmpty(assemblyLocation, "assemblyLocation");

			using (RegistryKey key = Registry.CurrentUser.CreateSubKey(RunLocation))
			{
				if (key == null)
				{
					throw new InvalidOperationException("The operation failed due to unknown reasons");
				}

				key.SetValue(keyName, assemblyLocation);
			}
		}

		/// <summary>
		/// Returns whether auto start is enabled.
		/// </summary>
		/// <param name="keyName">Registry Key Name</param>
		/// <param name="assemblyLocation">Assembly location (e.g. Assembly.GetExecutingAssembly().Location)</param>
		/// <returns><c>true</c> if the autostart has been already set, <c>false</c> otherwise.</returns>
		public bool IsAutoStartEnabled(string keyName, string assemblyLocation)
		{
			ParameterChecker.IsNotNullOrEmpty(keyName, "keyName");
			ParameterChecker.IsNotNullOrEmpty(assemblyLocation, "assemblyLocation");

			bool result = false;

			using (RegistryKey key = Registry.CurrentUser.OpenSubKey(RunLocation))
			{
				if (key != null)
				{
					object value = key.GetValue(keyName);
					if (value != null)
					{
						result = value.ToString() == assemblyLocation;
					}
				}
			}
			
			return result;
		}

		/// <summary>
		/// Unsets the autostart value for the assembly.
		/// </summary>
		/// <param name="keyName">Registry Key Name</param>
		public void UnSetAutoStart(string keyName)
		{
			ParameterChecker.IsNotNullOrEmpty(keyName, "keyName");

			using (RegistryKey key = Registry.CurrentUser.CreateSubKey(RunLocation))
			{
				if (key == null)
				{
					throw new InvalidOperationException("The operation failed due to unknown reasons");
				}

				key.DeleteValue(keyName);
			}
		}
	}
}